<template>
	<view class="container">
		<view class="header">
			<view class="stats">
				<view class="stat-item">
					<text class="label">总数</text>
					<text class="value">{{ pagination.total || 0 }}</text>
				</view>
				<view class="stat-item">
					<text class="label">在线</text>
					<text class="value online">{{ stats.online }}</text>
				</view>
				<view class="stat-item">
					<text class="label">离线</text>
					<text class="value offline">{{ stats.offline }}</text>
				</view>
				<view class="stat-item">
					<text class="label">故障</text>
					<text class="value fault">{{ stats.fault }}</text>
				</view>
			</view>
			<view class="search-bar">
				<input class="search-input" v-model="searchParams.keyword" placeholder="搜索设备名称/编号" confirm-type="search" @confirm="handleSearch" />
				<button class="btn-search" @click="handleSearch">搜索</button>
			</view>
		</view>

		<view class="filter">
			<view class="filter-tabs">
				<view 
					v-for="(filter, index) in filters" 
					:key="index"
					class="filter-tab"
					:class="{ active: currentFilter === index }"
					@click="onFilterChange({ currentIndex: index })"
				>
					{{ filter }}
				</view>
			</view>
		</view>
		
		<view class="actions">
			<button class="btn-group" @click="goGroupManagement">分组管理</button>
		</view>

		<scroll-view scroll-y class="list" @scrolltolower="loadMore">
			<view v-for="item in deviceList" :key="item.deviceId" class="card" @click="goDetail(item)">
				<view class="row">
					<text class="name">{{ item.deviceName || ('设备' + item.deviceId) }}</text>
					<text class="status" :style="{ color: getStatusColor(item.status) }">{{ getStatusText(item.status) }}</text>
				</view>
				<view class="row sub">
					<text>编号：{{ item.deviceCode || item.deviceId }}</text>
					<text>位置：{{ item.installLocation || '—' }}</text>
				</view>
				<view class="row sub">
					<text>类型：{{ item.deviceType || '—' }}</text>
					<text>负责人：{{ item.responsiblePerson || '—' }}</text>
				</view>
			</view>
			<view v-if="loading" class="loading">
				<text>加载中...</text>
			</view>
			<view v-if="!loading && (!deviceList || deviceList.length === 0)" class="empty">
				<text>暂无设备</text>
			</view>
		</scroll-view>

		<view class="fab" @click="createNew">
			<text class="fab-icon">+</text>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useDeviceStore } from '@/stores/device.js'
import { getDeviceList } from '@/api/device.js'

const deviceStore = useDeviceStore()

const loading = ref(false)
const deviceList = ref([])
const pagination = ref({
	pageNum: 1,
	pageSize: 10,
	total: 0
})

const searchParams = ref({
	keyword: '',
	deviceType: '',
	status: null
})

// 确保 searchParams 始终有默认值
if (!searchParams.value) {
	searchParams.value = {
		keyword: '',
		deviceType: '',
		status: null
	}
}

const filters = ['全部', '在线', '离线', '故障']
const currentFilter = ref(0)

// 统计信息
const stats = computed(() => {
	const stats = { online: 0, offline: 0, fault: 0 }
	if (deviceList.value && Array.isArray(deviceList.value)) {
		deviceList.value.forEach(device => {
			switch (device.status) {
				case 1: stats.online++; break
				case 2: stats.offline++; break
				case 3: stats.fault++; break
			}
		})
	}
	return stats
})

const getStatusColor = (status) => {
	const colorMap = {
		1: '#4cd964', // 在线 - 绿色
		2: '#999999', // 离线 - 灰色
		3: '#dd524d'  // 故障 - 红色
	}
	return colorMap[status] || '#999999'
}

const getStatusText = (status) => {
	const textMap = {
		1: '在线',
		2: '离线',
		3: '故障'
	}
	return textMap[status] || '未知'
}

// 获取设备列表
const fetchList = async (reset = true) => {
	try {
		loading.value = true
		if (reset) {
			pagination.value.pageNum = 1
			deviceList.value = []
		}
		
		const params = {
			pageNum: pagination.value.pageNum,
			pageSize: pagination.value.pageSize,
			...searchParams.value
		}
		
		const res = await getDeviceList(params)
		console.log('设备列表响应:', res)
		
		if (res && res.code === 200) {
			const data = res.obj
			const newList = data.list || data.records || []
			if (reset) {
				deviceList.value = newList
			} else {
				// 确保 deviceList.value 是数组
				if (!Array.isArray(deviceList.value)) {
					deviceList.value = []
				}
				deviceList.value.push(...newList)
			}
			pagination.value.total = data.total || 0
		} else {
			uni.showToast({
				title: res?.msg || '获取设备列表失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('获取设备列表失败:', error)
		uni.showToast({
			title: '网络错误，请重试',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 搜索
const handleSearch = () => {
	fetchList(true)
}

// 筛选变化
const onFilterChange = (e) => {
	currentFilter.value = e.currentIndex
	const statusMap = { 0: null, 1: 1, 2: 2, 3: 3 }
	searchParams.value.status = statusMap[e.currentIndex]
	fetchList(true)
}

// 加载更多
const loadMore = () => {
	if (deviceList.value && deviceList.value.length < pagination.value.total && !loading.value) {
		pagination.value.pageNum++
		fetchList(false)
	}
}

// 跳转详情
const goDetail = (item) => {
	deviceStore.setCurrentDevice(item)
	uni.navigateTo({ 
		url: `/pages/device/detail?deviceId=${item.deviceId}` 
	})
}

// 创建设备
const createNew = () => {
	uni.navigateTo({
		url: '/pages/device/form'
	})
}

// 分组管理
const goGroupManagement = () => {
	uni.navigateTo({
		url: '/pages/device/group'
	})
}

// 页面显示时检查是否需要刷新
onShow(() => {
	console.log('设备列表页面显示，检查是否需要刷新')
	
	// 检查是否有设备更新标志
	const deviceUpdated = uni.getStorageSync('device_updated')
	if (deviceUpdated) {
		console.log('检测到设备已更新，刷新列表')
		// 清除更新标志
		uni.removeStorageSync('device_updated')
		// 刷新设备列表
		fetchList(true)
	}
})

onMounted(() => {
	fetchList()
})
</script>

<style lang="scss" scoped>
.container {
	padding: 20rpx;
	background: #f8fffe;
	min-height: 100vh;
}

.header {
	background: #ffffff;
	border: 2rpx solid #e8f5e8;
	border-radius: 16rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.stats {
	display: flex;
	justify-content: space-between;
	margin-bottom: 16rpx;
}

.stat-item {
	flex: 1;
	text-align: center;
}

.label { font-size: 22rpx; color: #666; display: block; }
.value { font-size: 32rpx; font-weight: bold; color: #333; }
.value.online { color: #4cd964; }
.value.offline { color: #999; }
.value.fault { color: #dd524d; }

.search-bar {
	display: flex;
	gap: 12rpx;
}
.search-input {
	flex: 1;
	background: #f7f7f7;
	border-radius: 10rpx;
	padding: 16rpx 20rpx;
}
.btn-search {
	background-color: #2E7D32;
	color: #fff;
	border: none;
	border-radius: 10rpx;
	padding: 0 24rpx;
}

.filter { margin: 10rpx 0 20rpx; }

.filter-tabs {
	display: flex;
	background: #ffffff;
	border: 2rpx solid #e8f5e8;
	border-radius: 12rpx;
	overflow: hidden;
}

.filter-tab {
	flex: 1;
	height: 70rpx;
	line-height: 70rpx;
	text-align: center;
	font-size: 26rpx;
	color: #666;
	background: #ffffff;
	transition: all 0.3s;
	
	&.active {
		background: #2E7D32;
		color: #ffffff;
		font-weight: bold;
	}
}

.actions {
	margin-bottom: 20rpx;
}

.btn-group {
	width: 100%;
	height: 70rpx;
	background: linear-gradient(135deg, #4CAF50, #2E7D32);
	color: #ffffff;
	border: none;
	border-radius: 12rpx;
	font-size: 26rpx;
	box-shadow: 0 4rpx 12rpx rgba(46, 125, 50, 0.3);
}

.list { max-height: calc(100vh - 360rpx); }

.card {
	background: #ffffff;
	border: 2rpx solid #e8f5e8;
	border-radius: 14rpx;
	padding: 20rpx;
	margin-bottom: 16rpx;
	box-shadow: 0 4rpx 16rpx rgba(46,125,50,0.06);
}
.row { display: flex; justify-content: space-between; align-items: center; }
.row.sub { color: #666; font-size: 22rpx; margin-top: 10rpx; }
.name { font-size: 28rpx; font-weight: 600; color: #333; }
.status { font-size: 24rpx; }

.empty { text-align: center; color: #999; padding: 80rpx 0; }

.fab {
	position: fixed;
	right: 40rpx;
	bottom: 140rpx;
	width: 96rpx;
	height: 96rpx;
	border-radius: 50%;
	background: #2E7D32;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 10rpx 24rpx rgba(0,0,0,0.2);
}

.fab-icon {
	font-size: 40rpx;
	color: #ffffff;
	font-weight: bold;
}
</style>


